﻿/********************************************
*                                           *
*  zyg.sso.js                               *
*                                           *
*  zyg.iframe.autoFitHeight()               *
*                                           *
*  zyg.validateTip()                        *
*                                           *
*  zyg.sso.infoTable()                      *
*                                           *
********************************************/

(function($) {
    if (typeof (zyg) == 'undefined') {
        zyg = window.zyg = {};
    }

    // iframe 高度自适应
    zyg.iframe = {};

    zyg.iframe.autoFitHeight = function(id) {
        var fit = function() {
            $(id).each(function() {
                var bobo = $(this)[0];
                if (bobo && !window.opera) {
                    if (bobo.contentDocument && bobo.contentDocument.body.offsetHeight) {
                        bobo.height = bobo.contentDocument.body.offsetHeight + 60;
                    } else if (bobo.Document && bobo.Document.body.scrollHeight) {
                        bobo.height = bobo.Document.body.scrollHeight + 60;
                    }
                }
            });
        };

        if (window.attachEvent) {
            $(id).each(function() {
                $(this)[0].attachEvent("onload", fit);
            });
        }
        else if (window.addEventListener) {
            $(id).each(function() {
                $(this)[0].addEventListener("load", fit, false);
            });
        }
    }

    /* Validate form. */
    zyg.validateTip = function(formId, rules, options) {
        var settings = {
            debug: true,
            tipShow: true,
            tipId: 'validateTip',
            tipClass: 'validateTip',
            tipOffsetX: 0,
            tipOffsetY: 5,
            focusShow: true,
            msgTag: 'label',
            msgTagIdSuf: 'msg',
            msgTagClass: 'default',
            msgTagOkClass: 'ok',
            msgTagErrClass: 'err',
            controlOkClass: 'ok',
            controlErrClass: 'err',
            blurValidate: true
        };
        if (options != null) $.extend(settings, options);

        /*
        * rule template
        var ruleTemplate = {
        id: 'id',
        required: true,
        pattern: '',
        ok: 'Ok',
        err: 'error',
        tip: 'tip'
        };
        */

        var form = $("#" + formId);

        if (form.length < 1) return;

        var tipCon = "<div id='" + settings.tipId + "' class='" + settings.tipClass + "' style='display: none;'></div>";
        $("body").append(tipCon);

        // set tip id
        settings.tipId = '#' + settings.tipId;

        for (var r in rules) {
            (function() {
                var rule = rules[r];

                if (!rule.id || rule.id == '') return;

                var rt = {
                    id: 'id',
                    required: true,
                    pattern: '',
                    ok: 'Ok',
                    err: 'error',
                    tip: 'tip',
                    additional: function() { return true; }
                }; // rule template

                $.extend(rt, rule);
                rule = rt;

                var control = $("#" + rule.id);
                control.attr('pattern', rule.pattern);

                var msgTagId = rule.id + settings.msgTagIdSuf;
                var msgTag = $("<" + settings.msgTag + " id='" + msgTagId + "' class='" + settings.msgTagClass + "'></" + settings.msgTag + ">");
                msgTag.appendTo(control.parent());

                // tip
                if (settings.tipShow && rule.tip != '') {
                    var tip = $(settings.tipId);
                    control.hover(function() {
                        var offset = $(this).offset();
                        tip.html(rule.tip);

                        tip.css({
                            top: offset.top + $(this).height() + settings.tipOffsetY,
                            left: offset.left + settings.tipOffsetX,
                            display: 'block'
                        });
                    },
                    function() {
                        tip.css({ display: 'none' });
                    })
                    .focus(function() {
                        msgTag.attr("className", settings.msgTagClass);
                        tip.css({ display: 'none' });
                    }).blur(function() {
                        tip.css({ display: 'none' });
                    });
                }

                // focus show
                if (settings.focusShow) {
                    control.focus(function() {
                        var msgTag = $(this).parent().find("#" + $(this).attr('id') + settings.msgTagIdSuf);
                        msgTag.html(rule.tip);
                    });
                }

                // blur Validate
                if (settings.blurValidate) {
                    control.blur(function() {
                        var current = $(this);
                        var cv = true;

                        if (rule.required) {
                            cv &= zyg.validateTip.isValid(current);
                        } else {
                            if (current.val() != '') { // 若不为必填项且内容不为空
                                cv &= zyg.validateTip.isValid(current);
                            }
                        }

                        cv &= rule.additional();

                        var msgTag = current.parent().find("#" + current.attr('id') + settings.msgTagIdSuf);

                        if (cv) {
                            msgTag.removeClass(settings.msgTagErrClass);
                            msgTag.addClass(settings.msgTagOkClass);
                            msgTag.html(rule.ok);

                            current.removeClass(settings.controlErrClass);
                            current.addClass(settings.controlOkClass);
                        } else {
                            msgTag.removeClass(settings.msgTagOkClass);
                            msgTag.addClass(settings.msgTagErrClass);
                            msgTag.html(rule.err);

                            current.removeClass(settings.controlOkClass);
                            current.addClass(settings.controlErrClass);
                        }
                    });
                }
            })();
        }

        form.bind("submit", function(e) {
            var r = true;
            for (var s in rules) {
                (function() {
                    var rule = rules[s];
                    if (!rule.id) return;

                    var rt = {
                        id: 'id',
                        required: true,
                        pattern: '',
                        ok: '可用',
                        err: 'error',
                        tip: 'tip',
                        additional: function() { return true; }
                    }; // rule template

                    $.extend(rt, rule);
                    rule = rt;

                    var control = $("#" + rule.id);
                    var msgTag = $("#" + rule.id + settings.msgTagIdSuf);

                    var cv = true; // current valid

                    if (rule.required) {
                        cv &= zyg.validateTip.isValid(control);
                    } else {
                        if (control.val() != '') {
                            cv &= zyg.validateTip.isValid(control);
                        }
                    }

                    cv &= rule.additional();

                    if (cv) {
                        msgTag.addClass(settings.msgTagOkClass);
                        msgTag.html(rule.ok);

                        control.removeClass(settings.controlErrClass);
                        control.addClass(settings.controlOkClass);
                    } else {
                        msgTag.addClass(settings.msgTagErrClass);
                        msgTag.html(rule.err);

                        control.removeClass(settings.controlOkClass);
                        control.addClass(settings.controlErrClass);
                    }

                    r &= cv;
                })();
            }

            if (!r) {
                e.preventDefault();
            } else {
                if (settings.debug) {
                    e.preventDefault();
                    if (window.console) {
                        console.log('form submitted at ' + new Date());
                    } else {
                        alert('form submitted at ' + new Date());
                    }
                }
            }
        });
    }

    zyg.validateTip.isValid = function(elem) {
        var pattern = elem.attr('pattern');

        if (typeof (pattern) == 'undefined' || pattern == '') return true;
        var valReg = new RegExp(pattern, "g");

        var v = $.trim(elem.val());
        elem.val(v);

        if (valReg.test(v)) {
            return true;
        } else {
            return false;
        }
    }

    // zyg.sso
    zyg.sso = {};

    // 生成InfoTable
    zyg.sso.infoTable = function(options) {
        var settings = {
            debug: true,            // 是否处于调试模式
            id: '#infoTable',       // 标识
            head: true,             // 是否含有标题行
            zebra: true,            // 是否隔行交替效果
            evenClass: 'even',      // 隔行交替效果时偶数行的CSS类名
            oddClass: 'odd',        // 隔行交替效果时奇数行的CSS类名
            hover: true,            // 是否需要触发悬停事件
            hoverClass: 'hover',    // 悬停时的CSS类名
            checkAll: false,        // 是否包含全选
            checkChangedCallback: function(/*{id: 'tableId',checkedCount: 0}*/) { }
        };
        $.extend(settings, options);

        var tbs = $(settings.id);

        // return if no such table.
        if (tbs.length < 1) return;

        tbs.each(function() {
            $(this).removeAttr("rules").css({ borderWidth: "", borderCollapse: "" });
        });

        // 显示隔行效果
        if (settings.zebra) {
            if (settings.head) {
                tbs.each(function() {
                    $(this).find("> tbody > tr:even").not(":first").addClass(settings.evenClass);
                });
            } else {
                tbs.each(function() {
                    $(this).find("> tbody > tr:even").addClass(settings.evenClass);
                });
            }

            tbs.each(function() {
                $(this).find("> tbody > tr:odd").addClass(settings.oddClass);
            });
        }

        // 触发悬停事件
        if (settings.hover) {
            var hoverClass = settings.hoverClass;
            if (settings.head) {
                tbs.each(function() {
                    $(this).find("> tbody > tr").not(":first").hover(
                        function() {
                            $(this).addClass(hoverClass);
                        },
                        function() {
                            $(this).removeClass(hoverClass);
                        });
                });
            } else {
                tbs.each(function() {
                    $(this).find("> tbody > tr").hover(
                        function() {
                            $(this).addClass(hoverClass);
                        },
                        function() {
                            $(this).removeClass(hoverClass);
                        });
                });
            }
        }

        // 触发全选事件
        if (settings.checkAll && settings.head) {
            var checkedCount = 0;

            tbs.each(function() {
                var ct = $(this); // 当前table
                $(this).find("> tbody > tr:first :checkbox").click(function() {
                    if ($(this).attr("checked")) {
                        ct.find(":checkbox").attr("checked", "checked");
                    } else {
                        ct.find(":checkbox").attr("checked", "");
                    }

                    onCheckboxChanged(ct);
                });

                $(this).find(":checkbox").not(":first").click(function() {
                    onCheckboxChanged(ct);
                });
            });

            // checkbox changed event.
            var onCheckboxChanged = function(table) {
                var checkedCount = 0;
                var allChecked = true;

                table.find(":checkbox").not(":first").each(function(index, domEle) {
                    var curChecked = $(domEle).attr("checked");
                    allChecked &= curChecked;

                    if (curChecked) checkedCount += 1;
                });

                if (allChecked) {
                    table.find(":checkbox").filter(":first").attr("checked", "checked");
                } else {
                    table.find(":checkbox").filter(":first").attr("checked", "");
                }

                // triger callback
                settings.checkChangedCallback({ id: table.attr("id"), checkedCount: checkedCount });
            }
        }
    }

    zyg.sso.textbox = function(options) {
        var settings = {
            id: '',
            defaultClass: 'text',
            hoverClass: 'hoverText',
            focusClass: 'focusText'
        };
        $.extend(settings, options);

        var tbs;

        if (settings.id == '') {
            tbs = $(":text,:password,textarea");
        } else {
            tbs = $(settings.id);
        }

        tbs.each(function() {
            $(this)
                .addClass(settings.defaultClass)
                .focus(function() {
                    $(this).addClass(settings.focusClass);
                }).blur(function() {
                    $(this).removeClass(settings.focusClass);
                }).hover(function() {
                    $(this).addClass(settings.hoverClass);
                },
                function() {
                    $(this).removeClass(settings.hoverClass);
                });
        });
    }


    // 显示当前时间
    zyg.sso.showTime = function(id) {
        this.show = function() {
            var now = new Date();
            var year = now.getYear();
            var month = now.getMonth() + 1;
            var day = now.getDate();
            var hour = now.getHours();
            var minute = now.getMinutes();
            var second = now.getSeconds();

            year = year > 1900 ? year : year + 1900;

            var s = '当前时间: ' + year + '年' + month + '月' + day + '日&nbsp;' + hour + '点' + minute + '分' + second + '秒';
            $(id).empty();
            $(id).append(s);
        }

        setInterval(this.show, 1000);
    }

    // Theme
    zyg.sso.theme = function() {
        if (typeof ($.cookie) == 'undefined')
            return;

        var themeUL = $("#theme");
        if (themeUL.length < 1) return;

        var theme = $.cookie('theme');

        $("#theme-" + theme, themeUL).addClass('current');

        $("#theme-gray", themeUL).click(function() {
            if (theme == 'gray') return;

            themeUL.find("a").removeClass('current');
            $(this).addClass('current');

            // $("<link href='style/" + theme + "/core.css' rel='stylesheet' type='text/css' charset='utf-8' />").appendTo($('head'));
            $.cookie("theme", "gray");

            window.location.reload();
        });
        $("#theme-blue", themeUL).click(function() {
            if (theme == 'blue') return;

            themeUL.find("a").removeClass('current');
            $(this).addClass('current');

            // $("<link href='style/" + theme + "/core.css' rel='stylesheet' type='text/css' charset='utf-8' />").appendTo($('head'));

            $.cookie("theme", "blue");

            window.location.reload();
        });
        $("#theme-green", themeUL).click(function() {
            if (theme == 'green') return;

            themeUL.find("a").removeClass('current');
            $(this).addClass('current');

            $.cookie("theme", "green");

            window.location.reload();
        });
        $("#theme-red", themeUL).click(function() {
            if (theme == 'red') return;

            themeUL.find("a").removeClass('current');
            $(this).addClass('current');

            $.cookie("theme", "red");

            window.location.reload();
        });
    }
})(jQuery);